<template>
    <div class="featured-class">
        <!-- Hero Section 骨架屏 -->
        <div class="hero-section" v-if="loading">
            <a-skeleton :paragraph="{ rows: 2 }" :title="{ width: '60%' }" active />
            <a-row :gutter="[16, 16]" class="category-buttons">
                <a-col :xs="24" :sm="12" :md="6" v-for="i in 4" :key="i">
                    <a-skeleton.Button style="width: 100%; height: 70px;" active />
                </a-col>
            </a-row>
        </div>

        <!-- Hero Section 实际内容 -->
        <div class="hero-section" v-else>
            <h1 class="main-title">NEW STYLE, NEW YOU</h1>
            <p class="sub-title">Radiate <em>new energy</em> with these latest looks</p>

            <a-row :gutter="[16, 16]" class="category-buttons">
                <a-col :xs="24" :sm="12" :md="6" v-for="(category, index) in getSonclassifyDataChildren" :key="index">
                    <a-button class="category-btn" @click="scrollToSection(category.id)">{{ category.name }}</a-button>
                </a-col>
            </a-row>
        </div>

        <!-- 特色区域骨架屏 -->
        <template v-if="loading">
            <div v-for="i in 3" :key="i" class="featured-section">
                <a-row type="flex" align="middle" :gutter="[90, 0]">
                    <a-col :span="24" :lg="16">
                        <a-row :gutter="[16, 16]" class="product-grid">
                            <a-col :xs="24" :sm="12" :md="12" :lg="6" v-for="j in 8" :key="j">
                                <div class="product-card">
                                    <a-skeleton.Image style="width: 100%; height: 312px;" active />
                                    <div class="product-info">
                                        <a-skeleton :paragraph="{ rows: 2 }" active />
                                    </div>
                                </div>
                            </a-col>
                        </a-row>
                    </a-col>
                    <a-col :span="24" :lg="8">
                        <div class="feature-image">
                            <a-skeleton :paragraph="{ rows: 1 }" :title="{ width: '80%' }" active />
                            <a-skeleton.Image style="width: 418px; height: 600px;" active />
                        </div>
                    </a-col>
                </a-row>
            </div>
        </template>

        <!-- 特色区域实际内容 -->
        <div v-else v-for="(section, index) in sections" :key="index" :id="'section-' + section.id" class="featured-section">
            <a-row type="flex" align="middle" :gutter="[90, 0]">
                <!-- 内容部分 - 可以在左侧或右侧 -->
                <a-col :span="24" :lg="16" :order="section.imageRight ? 1 : 2">
                    <a-row :gutter="[16, 16]" class="product-grid">
                        <a-col :xs="24" :sm="12" :md="12" :lg="6" v-for="(product, pIndex) in section.goods.slice(0, 8)" :key="pIndex">
                            <div class="product-card">
                                <div class="product-image">
                                    <a :href="`/product/${product.url}.html`" :title="product.name" target="_self" >
                                        <img  :src="product.images[0]" :alt="product.name" :title="product.name"/>
                                    </a>
                                    <div class="product-actions">
                                        <a-button class="add-btn"  @click="addCart(product)">Add+</a-button>
                                    </div>
                                </div>
                                <div class="product-info">
                                    <div class="product-name"><h3>{{ product.name }}</h3>
                                        <HeartFilled v-if="product.is_favorited == 1" @click.stop="toggleFavorite(product)"/>
                                        <heart-outlined v-else class="wishlist-icon" :style="{ color: product.is_favorited ? '#ff4d4f' : '' }" @click.stop="toggleFavorite(product)"/>
                                    </div>

                                    <p class="product-price">${{ product.max_origin_price}}</p>
                                </div>
                            </div>
                        </a-col>
                    </a-row>
                </a-col>

                <!-- 图片部分 - 可以在左侧或右侧 -->
                <a-col :span="24" :lg="8" :order="section.imageRight ? 2 : 1">
                    <div class="feature-image">
                        <h2>{{ section.title }}</h2>
                        <a :href="`/product/${section.url}.html`" target="_self" :title="section.title">
                            <a-image :src="section.image" :alt="section.title" :preview="false" :title="section.title" />
                        </a>

                    </div>
                </a-col>
            </a-row>
        </div>
    </div>
    <a-modal v-model:open="open" width="1200px" title="Product Details" :footer="null">
        <ProductDetail.default v-if="open && goodId" :goodId="goodId" @buy="handleBuy" />
    </a-modal>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { HeartOutlined } from '@ant-design/icons-vue';
import {getSonclassify } from '@/api/home'
import * as ProductDetail from '@/components/ProductDetail.vue';
import {delFavorite, getClassifyAttributes, getFavoriteList} from "@/api/goods";
import {addFavorite} from "@/api/details"
import SVG_ICONS from "@/assets/SVG_ICONS.ts";
import {message} from "ant-design-vue";
import {Session} from "@/utils/storage.ts";
import {useRouter} from "vue-router";
import {getToken} from "@/utils/auth.ts";
import { useRoute } from 'vue-router';

const route = useRoute();
// 公共变量
const router = useRouter();
const isLogin = ref(false)
interface Product {
    id: number;
    url: string;
    name: string;
    price: number;
    image: string;
    isNew: boolean;
    isSustainable: boolean;
}

interface Section {
    id: number;
    url: string;
    title: string;
    image: string;
    imageRight: boolean;
    goods: any[];
}

interface ApiResponse<T> {
    code: number;
    result: T[];
    message: string;
}

interface CategoryItem {
    id: number;
    url: string;
    name: string;
    icon: string;
    children: any[];
    goods: any[];
}

const open = ref<boolean>(false);
const goodId = ref<string | null>(null);
const getSonclassifyDataChildren = ref<CategoryItem[]>([])

// 特色区域数据
const sections = ref<Section[]>([]);
const sectionsData = ref<Section[]>([])
// 添加 loading 状态
const loading = ref(true);

onMounted(() => {
     // 检测是否登录
  if (getToken()) {
    isLogin.value = true
  }
  featuredclassify()
})

const featuredclassify = async()=>{
  loading.value = true; // 开始加载时显示骨架屏
  try {
    const res = await getSonclassify(route.query.id,8)

    if (res.code === 200 && res.result && res.result.length > 0) {
      getSonclassifyDataChildren.value = res.result[0].children
      // 特色区域数据替换原来sections数据
      sectionsData.value = res.result[0].children.map((item: CategoryItem, index: number) => {
        return {
          id: item.id,
          title: item.name,
          image: item.icon,
          imageRight: index % 2 === 1, // 交替显示图片在左侧或右侧
          goods: item.goods,
          url: item.url
        }
      })

      // 更新sections数据
      sections.value = sectionsData.value
    }
  } catch (error) {
    console.error('Failed to fetch featured classify:', error);
    message.error('加载失败，请稍后重试');
  } finally {
    loading.value = false; // 加载完成后隐藏骨架屏
  }
}

// 添加购物车方法

const addCart = (product: ProductType) => {
  // 防止穿透点击
  if (open.value) {
    return;
  }
  // 打开购买弹窗
  open.value = true;

  goodId.value = String(product.id);
}
// 添加滚动到指定区域的方法
const scrollToSection = (sectionId: number) => {
  const element = document.getElementById('section-' + sectionId)
  if (element) {
    element.scrollIntoView({
      behavior: 'smooth',
      block: 'start'
    })
  }
}
// 处理购买按钮点击
const handleBuy = (data?: BuyData) => {
  open.value = false;
};
// 处理收藏功能
const toggleFavorite = async (product: any) => {
  if (isLogin.value) {
    // 登录状态
    if (product.is_favorited == 0) {
      await addFavorite({
        goods_id: product.id
      }).then(res => {
        if (res.code === 200) {
          message.success('Successfully collected');
          getFavoriteListApi()
          // 更新商品收藏状态
          product.is_favorited = 1
        } else {
          product.is_favorited = 0
          message.error(res.data.msg);
        }
      })
    } else {
      await delFavorite({
        goods_id: product.id
      }).then(res => {
        if (res.code === 200) {
          getFavoriteListApi()
          message.success('Cancel collection successfully');
          // 更新商品收藏状态
          product.is_favorited = 0
        } else {
          product.is_favorited = 1
          message.error(res.data.msg);
        }
      })

    }
  } else {
    // 未登录，提示登录
    message.warning('Please login first');
    router.push('/login');
  }
}
// 获取收藏列表
const getFavoriteListApi = async () => {
  await getFavoriteList().then(res => {
    if (res.code == 200) {
      Session.set('collectList', res.result)
    } else {
      message.error(res.msg)
    }
  })
}
</script>

<style lang="scss" scoped>
.featured-class {
    max-width: 1500px;
    margin: 46px auto;
    padding: 20px;
}

.hero-section {
    text-align: center;
    margin-bottom: 50px;

    .main-title {
        font-size: 50px;
        font-weight: 300;
        letter-spacing: 2px;
        margin-bottom: 10px;
        text-transform: uppercase;
        font-family: 'freight-display-pro', serif;
        font-style: italic !important;
    }

    .sub-title {
        font-size: 40px;
        font-weight: 300;
        margin-bottom: 30px;
        font-family: freight-display-pro, serif;
        -webkit-font-smoothing: antialiased;
        em {
            font-style: italic;
        }
    }

    .category-buttons {
        max-width: 1400px;
        margin: 0 auto;

        .category-btn {
            width: 100%;
            height: 70px;
            border-radius: 55px;
            font-size: 24px;
            background-color: #f2f2f2;
            border: none;
            font-family: 'freight-display-pro', serif;
            &:hover {
                background-color: #e6e6e6;
            }
        }
    }
}

.featured-section {
    margin-top: 30px;

    .ant-row {
        margin-left: -20px !important;
        margin-right: -20px !important;
    }

    h2 {
        font-size: 28px;
        font-weight: 300;
        margin-bottom: 20px;
    }

    .feature-image {
        width: 418px;
        height: 600px;
        overflow: hidden;
        position: relative;
        margin: 0 auto;

        h2 {
            font-size: 34px;
            position: absolute;
            top: 10%;
            left: 50%;
            transform: translateX(-50%);
            z-index: 1;
            color: #000;
            font-weight: 300;
            text-align: center;
            width: 100%;
            margin: 0;
            padding: 0 10px;
            font-family: freight-display-pro, serif;
        }

        img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    }

    .product-grid {
        margin-top: 20px;
    }

    .product-card {
        margin-bottom: 30px;

        .product-image {
            position: relative;
            width: 100%;
            height: 312px;
            img {
                width: 100%;
                height: 100%;
                object-fit: cover;
                display: block;
            }

            .product-actions {
                position: absolute;
                bottom: 10px;
                right: 0;
                display: flex;
                justify-content: space-between;
                padding: 0 10px;

                .add-btn {
                    background-color: white;
                    color: black;
                    border: none;
                    border-radius: 5px;
                    border:1px solid #ccc;
                    padding: 0 10px;
                }
            }
        }

        .product-info {
            padding: 10px 0;

            .product-name {
                display: flex;
                justify-content: space-between;
            }

            h3 {
                font-size: 16px;
                font-weight: 400;
                margin-bottom: 5px;
                // 超出部分显示省略号
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }

            .product-price {
                font-size: 15px;
                font-weight: 500;
                margin-bottom: 10px;
            }

            .product-tags {
                display: flex;
                gap: 10px;

                .tag {
                    font-size: 12px;
                    padding: 2px 0;

                    &.sustainable {
                        color: green;
                    }
                }
            }
        }
    }
}

// 确保两个section之间有足够间距
.featured-section + .featured-section {
    margin-top: 60px;
    padding-top: 20px;
    /*border-top: 1px solid #f0f0f0;*/
}

@media (max-width: 768px) {
    .hero-section {
        .main-title {
            font-size: 24px;
        }

        .sub-title {
            font-size: 16px;
        }
    }

    .featured-section {
        h2 {
            font-size: 22px;
        }
    }
}

// 添加骨架屏相关样式
.featured-section {
    .ant-skeleton {
        width: 100%;
    }

    .ant-skeleton-image {
        width: 100%;
        height: 100%;
    }
}

.product-card {
    .ant-skeleton {
        padding: 10px;
    }
}
</style>
